var site = {
    port: 8888,
    host: "www.test1.ru"
};
includeSocket();

var key = {
    left:  37,
    right: 39,
    up:    38,
    down:  40,
    a:     65,
    w:     87,
    d:     68,
    s:     83
};

function userDraw( context, user, color )
{  
    context.save();
    context.fillStyle = color;
    context.fillRect( user.x, user.y, user.width, user.height );
    context.restore();
}

function drawFrame( context, canvas, user, myId )
{
    context.clearRect( 0, 0, canvas.width, canvas.height );
    for ( var i = 0; i < user.length; i++ )
    {   
        if ( user[i].catching )
        {
            userDraw( context, user[i], 'red' );
        }
        else if ( i == myId )
        {
            userDraw( context, user[i], 'black' );
        }
        else
        {
            userDraw( context, user[i], 'silver' );
        }
    }
}

function handler( event, user, myId, key )
{
    switch( event.keyCode )
    {
      case key.up:
        user[myId].y = ( user[myId].y > 0 ) ? user[myId].y - user[myId].speed : 0;
        break;
      case key.down:
        user[myId].y = ( user[myId].y < 440 ) ? user[myId].y + user[myId].speed : 440;
        break;
      case key.left:
        user[myId].x = ( user[myId].x > 0   ) ? user[myId].x - user[myId].speed : 0;
        break;
      case key.right:
        user[myId].x = ( user[myId].x < 580 ) ? user[myId].x + user[myId].speed : 580;
        break;
      default:
        break;
    }
    socket.emit( 'keyPress', user[myId].x, user[myId].y, myId );
}

window.onload = function()
{
    var canvas   = document.getElementById( 'canvas' );
    var context  = canvas.getContext( '2d' );
    var myId     = 0;
    var user     = new Array();

    socket.on( 'createUser',
    function( arr, id )
    {
        user = arr;
        myId = id;
    } );
    
    socket.on( 'newData',
    function( data )
    {
        user = data;
        animate();
    } );
    
    socket.on( 'notEnter',
    function( data )
    {
        alert( data );
        document.location.href = "/";
    } );
    
    document.onkeydown = function( event )
    {
        handler( event, user, myId, key );
    }
    
    function animate()
    {
        requestAnimationFrame( animate );
        drawFrame( context, canvas, user, myId );
    }
    animate();
}